package gen.tools.delivery;

import gen.tools.Widgets;
import gen.tools.structures.IDS;
import gen.tools.structures.InfoStruc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QuerySystemList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QuerySystemList() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		final IDS ids = new IDS();
		final ArrayList<InfoStruc> ises = new ArrayList<InfoStruc>();
		String sql = "SELECT sysSN, sysname FROM envsystemlist WHERE isLocalSys='f' ORDER BY sysname";
		
		
		try {
			conn = wid.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while ( rs.next()) {
				final InfoStruc is = new InfoStruc();
				is.setId( String.valueOf( rs.getInt("sysSN") ) );
				is.setName( rs.getString("sysname") );
				ises.add(is);
			}
			
			sql = "SELECT sysSN, sysname FROM envsystemlist WHERE isLocalSys='t'";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			rs.next();
			
			ids.setId( String.valueOf( rs.getInt("sysSN") ) );
			ids.setName( rs.getString("sysname") );
			ids.setIses(ises);
		}  catch ( Exception e) {
			wid.errLog(e);
		}  finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}

		response.getWriter().write(new Gson().toJson(ids));	
	
	}

}
